package initialize

import (
	"bufio"
	"fmt"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"os"
	"strings"
	"time"
)

type sqlLog struct {
	log *zap.SugaredLogger
}

func (l *sqlLog) Write(p []byte) (n int, err error) {
	var sql []string
	sc := bufio.NewScanner(strings.NewReader(string(p)))
	for sc.Scan() {
		sql = append(sql, sc.Text())
	}
	l.log.Debug(sql[1])
	return 0, nil
}

func MustNewMysql(dsn string, zaplog *zap.SugaredLogger) *gorm.DB {
	newLogger := logger.New(
		log.New(&sqlLog{zaplog}, "", log.LstdFlags),
		logger.Config{
			SlowThreshold: 1 * time.Second,
			LogLevel:      logger.Info,
			Colorful:      false,
		},
	)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger:                                   newLogger,
		DisableForeignKeyConstraintWhenMigrating: true,
		SkipDefaultTransaction:                   true,
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
	})

	if err != nil {
		fmt.Println("连接数据库失败，请检查参数：", err)
		os.Exit(1)
	}

	sqlDB, _ := db.DB()
	// SetMaxIdleCons 设置连接池中的最大闲置连接数。
	sqlDB.SetMaxIdleConns(10)

	// SetMaxOpenCons 设置数据库的最大连接数量。
	sqlDB.SetMaxOpenConns(10)

	// SetConnMaxLifetiment 设置连接的最大可复用时间。
	sqlDB.SetConnMaxLifetime(10 * time.Second)

	return db
}
